<script lang="ts" setup>
  import { ref, watch, onMounted, onUnmounted } from 'vue';
  import { debounce } from 'lodash'; // 或手动实现简单防抖
  import * as echarts from 'echarts/core';
  const props = defineProps({
    graphDataUpper: Array<any>,
    graphDataAnneal: Array<any>,
    graphDataNext: Array<any>,
    graphDataLower: Array<any>,
    xdata: Array<any>,
    change: Number,
  });

  // const changeColor = ref(false);
  const CURRENT_NAME = '当前卷实时退火曲线';
  const PREVIOUS_NAME = '上一卷实时退火曲线';
  const chartRef = ref<HTMLElement | null>(null);
  let chartInstance: echarts.ECharts | null = null;
  const lastChange = ref<number | undefined>(0);
  const option = ref<any>({
    grid: {
      top: '8%',
      left: '4%',
      right: '2%',
      bottom: '10%',
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: (params: any[]) => {
        if (params.length === 0) return '';
        let content = `<div style="color:black; font-weight:bold;">${params[0].name}</div>`;
        params.forEach((point) => {
          if (point.value !== null && point.value !== 0 && point.value) {
            content += `
              <div style="display:flex; align-items:center; margin:2px 0;">
                <span style="width:8px; height:8px; border-radius:50%;
                  background-color:${point.color}; margin-right:5px;"></span>
                <span style="color:black;">${point.seriesName}: ${point.value}</span>
              </div>
            `;
          }
        });
        return content;
      },
    },
    xAxis: {
      data: [],
      type: 'category',
      axisLabel: {
        color: '#fff',
      },
      axisTick: {
        show: false,
      },
      axisLine: {
        show: false,
      },
      z: 10,
    },
    yAxis: {
      color: '#fff',
      name: 'mm',
      nameTextStyle: {
        color: '#fff',
        fontSize: 12,
      },
      boundaryGap: ['0', '10%'],
      axisLine: {
        show: true,
      },
      axisTick: {
        show: true,
      },
      axisLabel: {
        color: '#fff',
      },
      splitLine: {
        show: false,
      },
      scale: true,
    },
    series: [
      {
        type: 'line',
        name: '上限',
        data: [],
        symbol: 'none',
        lineStyle: {
          width: 1,
          // color: '#00baff',
          color: 'white',
        },
        itemStyle: {},
        force: {
          layoutAnimation: false,
        },
        symbolSize: 1,
        smooth: false, //曲线or折线
      },
      {
        type: 'line',
        name: CURRENT_NAME,
        data: [],
        symbol: 'none',
        lineStyle: {
          width: 2,
          color: '#00baff',
        },
        itemStyle: {},
        force: {
          layoutAnimation: false,
        },
        symbolSize: 1,
        smooth: true,
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(0, 186, 255, 0.6)' },
            { offset: 1, color: 'rgba(0, 186, 255, 0.1)' },
          ]),
        },
      },
      {
        type: 'line',
        name: '下一卷实时退火曲线',
        data: [],
        symbol: 'none',
        lineStyle: {
          width: 2,
          color: '#47ffb8',
        },
        itemStyle: {},
        force: {
          layoutAnimation: false,
        },
        symbolSize: 1,
        smooth: true,
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(71, 255, 184, 0.6)' },
            { offset: 1, color: 'rgba(71, 255, 184, 0.1)' },
          ]),
        },
      },
      {
        type: 'line',
        name: '下限',
        data: [],
        symbol: 'none',
        lineStyle: {
          width: 1,
          // color: '#2af598',
          color: 'white',
        },
        itemStyle: {},
        force: {
          layoutAnimation: false,
        },
        smooth: false,
        symbolSize: 1,
      },
    ],
  });

  const initCharts = () => {
    try {
      lastChange.value = props.change;
      option.value.series[1].name = CURRENT_NAME;

      option.value.xAxis.data = props.xdata;
      option.value.series[0].data = props.graphDataUpper;
      option.value.series[1].data = props.graphDataAnneal;
      option.value.series[2].data = props.graphDataNext;
      option.value.series[3].data = props.graphDataLower;

      // 计算 Y 轴范围（合并所有数据）
      const allData = [
        ...(props.graphDataUpper ?? []),
        ...(props.graphDataLower ?? []),
        ...(props.graphDataNext ?? [].map((value: any) => value && value != null && value != 0)),
        ...(props.graphDataAnneal ?? [].map((value: any) => value && value !== null && value !== 0)),
      ];
      let min = Math.floor(Math.min(...allData));
      let max = Math.ceil(Math.max(...allData));

      if (max - min <= 25) {
        option.value.yAxis.min = min - 1;
        option.value.yAxis.max = max + 1;
      } else if (max - min > 30) {
        option.value.yAxis.min = min - 3;
        option.value.yAxis.max = max + 3;
      } else if (max - min > 35) {
        option.value.yAxis.min = min - 5;
        option.value.yAxis.max = max + 5;
      } else if (max - min > 100) {
        option.value.yAxis.min = min - 10;
        option.value.yAxis.max = max + 10;
      } else {
        option.value.yAxis.min = min - 20;
        option.value.yAxis.max = max + 20;
      }

      if (chartRef.value && !chartInstance) {
        chartInstance = echarts.init(chartRef.value);
        chartInstance?.setOption(option.value, true);
      }
    } catch (error) {
      console.error('退火曲线初始化失败:', error);
    }
  };

  const updateChart = debounce(() => {
    try {
      if (props.change == 0) {
        option.value.series[1].name = CURRENT_NAME;
        option.value.series[2].name = PREVIOUS_NAME;
      }
      if (lastChange.value != props.change) {
        lastChange.value = props.change;
        [option.value.series[1].name, option.value.series[2].name] =
          option.value.series[1].name === CURRENT_NAME ? [PREVIOUS_NAME, CURRENT_NAME] : [CURRENT_NAME, PREVIOUS_NAME];
      }

      option.value.xAxis.data = props.xdata;
      option.value.series[0].data = props.graphDataUpper;
      option.value.series[1].data = props.graphDataAnneal;
      option.value.series[2].data = props.graphDataNext;
      option.value.series[3].data = props.graphDataLower;

      // 计算 Y 轴范围（合并所有数据）
      const allData = [
        ...(props.graphDataUpper ?? []).filter((value: any) => value != null && value != undefined && value != 0),
        ...(props.graphDataLower ?? []).filter((value: any) => value != null && value != undefined && value != 0),
        ...(props.graphDataNext ?? []).filter((value: any) => value != null && value != undefined && value != 0),
        ...(props.graphDataAnneal ?? []).filter((value: any) => value != null && value != undefined && value != 0),
      ];
      let min = Math.floor(Math.min(...allData));
      let max = Math.ceil(Math.max(...allData));

      if (max - min <= 25) {
        option.value.yAxis.min = min - 1;
        option.value.yAxis.max = max + 1;
      } else if (max - min > 30) {
        option.value.yAxis.min = min - 3;
        option.value.yAxis.max = max + 3;
      } else if (max - min > 35) {
        option.value.yAxis.min = min - 5;
        option.value.yAxis.max = max + 5;
      } else if (max - min > 100) {
        option.value.yAxis.min = min - 10;
        option.value.yAxis.max = max + 10;
      } else {
        option.value.yAxis.min = min - 20;
        option.value.yAxis.max = max + 20;
      }

      if (chartRef.value && chartInstance) {
        chartInstance.setOption(option.value, true);
      }
    } catch (error) {
      console.error('退火曲线更新失败:', error);
    }
  }, 100); // 防抖 100ms

  //props.graphDataUpper, props.graphDataAnneal, props.graphDataLower,
  watch(
    () => [props.xdata, props.graphDataUpper, props.graphDataLower],
    () => updateChart(),
    { deep: true }
  );

  onMounted(() => {
    // 确保在 DOM 加载完成后更新图表
    setTimeout(() => {
      initCharts();
    }, 1000);

    // 添加窗口大小变化监听
    window.addEventListener('resize', updateChart);
  });

  onUnmounted(() => {
    // 移除窗口大小变化监听
    window.removeEventListener('resize', updateChart);
    updateChart.cancel();
  });
</script>

<template>
  <div ref="chartRef" class="chart-container"></div>
</template>

<style scoped>
  .chart-container {
    width: 100%;
    height: 100%;
  }
</style>
